package com.example.demo.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author chenqiuran
 * @decription AOP日志
 * @date 2021/8/29
 */
//@Aspect
//@Component
public class WebLogAspect {

    private final Logger logger = LogManager.getLogger(this.getClass());

    @Pointcut(value = "execution(public * com.example.demo.controller..*.*(..))")
    public void webLog() {
    }

    /**
     * @Author chenqiuran
     * @Description //TODO 请求进入之前，日志记录
     * @Date 16:44 2021/8/29
     * @Param [joinPoint]
     * @return void
     **/
    @Before(value = "webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 接收到请求，打印请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求内容
        logger.info("URL : {}",request.getRequestURL().toString());
        logger.info("HTTP_METHOD : {}",request.getMethod());
        logger.info("IP : {}",request.getRemoteAddr());
        logger.info("CLASS_METHOD : {}",joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        logger.info("ARGS : {}",Arrays.toString(joinPoint.getArgs()));
    }

    /**
     * @Author chenqiuran
     * @Description //TODO 请求处理完成，返回日志记录
     * @Date 16:44 2021/8/29
     * @Param [ret]
     * @return void
     **/
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) {
        if(ret!=null){
            logger.info("请求处理完成，返回数据：{}", ret.toString());
        }
    }
}


